package com.paipaideli.ui.mine.head;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.common.utils.StringUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.ui.mine.head.bean.BankBean;
import com.paipaideli.ui.mine.safety.MyBankActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 提现
 */
public class CashActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.lin_bank_add)
    LinearLayout lin_bank_add;
    @BindView(R.id.tv_cash_priceall)
    TextView tv_cash_priceall;
    @BindView(R.id.et_cash_price)
    EditText et_cash_price;
    @BindView(R.id.tv_cash_kyprice)
    TextView tv_cash_kyprice;
    @BindView(R.id.tv_cash_bank)
    TextView tv_cash_bank;
    @BindView(R.id.btn_tx)
    Button btn_tx;
    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;

    private double ye;
    private List<BankBean.Data> list = new ArrayList<>();
    private String bankId;
    private String bankNum;

    @Override
    public int getContentView() {
        return R.layout.activity_cash;
    }

    java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("提现");
        ye = getIntent().getDoubleExtra("price", 0.00);
        tv_cash_kyprice.setText("您可提现金额：￥" + df.format(ye) + "");
        //返回
        top_back.setOnClickListener(o ->
                finish()
        );

        //全部提现
        addDisposable(RxView.clicks(tv_cash_priceall)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    et_cash_price.setText(df.format(ye) + "");
                }));

        //去提现
        addDisposable(RxView.clicks(btn_tx)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    String price = et_cash_price.getText().toString().trim();
                    if (!TextUtils.isEmpty(price) && Double.valueOf(price) > 0) {
                        if (Double.valueOf(price) > ye) {
                            ToastUtil.show("请输入正确的提现金额");
                        } else {
                            cash();
                        }
                    } else {
                        ToastUtil.show("请输入正确的提现金额");
                    }
                }));

        //添加银行卡
        RxView.clicks(lin_bank_add)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    Intent intent = new Intent(CashActivity.this, MyBankActivity.class);
                    intent.putExtra("which", "1");
                    startActivityForResult(intent, 1);
                }, throwable -> {
                });
    }

    @Override
    protected void onStart() {
        super.onStart();

        getDate();
    }

    //获取银行卡数据
    private void getDate() {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().bank(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        if (request.data.size() != 0) {
                            list.addAll(request.data);
                            if (list.size() > 0) {
                                bankNum = list.get(0).bankNumber;
                                tv_cash_bank.setText(list.get(0).bankName + "(尾号" + bankNum.substring(bankNum.length() - 4) + ")");
                                bankId = list.get(0).id;
                            } else {
                                tv_cash_bank.setText("请添加银行卡");
                            }
                        }else {
                            tv_cash_bank.setText("请添加银行卡");
                        }
                        bg_statusview.finish();
                        ToastUtil.show(request.msg);
                    } else {
                        bg_statusview.finish();
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    private void cash() {
        String money = et_cash_price.getText().toString();
        if (!StringUtil.isEmpty(money)) {
            JSONObject requestData = new JSONObject();
            try {
                requestData.put("amount", money);
                requestData.put("bankId", bankId);
            } catch (Exception e) {
                e.getMessage();
            }
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
            bg_statusview.showLoading();
            Api.getInstanceGson().apply(body)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(request -> {
                        if (request.getCode().equals("200")) {
                            finish();
                            bg_statusview.finish();
                            ToastUtil.show(request.getMessage());
                        } else {
                            bg_statusview.finish();
                            ToastUtil.show(request.getMessage());
                        }
                    }, throwable -> {
                        bg_statusview.finish();
                        Log.e(TAG, "error", throwable);
                    });
        } else {
            ToastUtil.show("请输入提现金额！");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1:
                    Bundle bundle = data.getExtras();
                    String bankName = bundle.getString("bankName");
                    bankNum = bundle.getString("bankNum");
                    bankId = bundle.getString("bankId");
                    tv_cash_bank.setText(bankName + "(尾号" + bankNum.substring(bankNum.length() - 4) + ")");
                    break;
            }
        }
    }
}
